#!/usr/bin/env python

"""
Calculate median values

"""
def unsorted_median(values):
    values = sorted(values)
    return sorted_median(values)
    
def sorted_median(values):
    if len(values) % 2 == 1:
        return values[(len(values)-1)/2]
    else:
        lower = values[len(values)/2-1]
        upper = values[len(values)/2]

    try:
        m = (lower + upper) / 2.0  
        return m
    except:
        return lower

import unittest

class _test_median(unittest.TestCase):

    #       self.assertEqual(self.seq, range(10))
    #       self.assert_(element in self.seq)
    #       self.assertRaises(ValueError, random.sample, self.seq, 20)



    def test_unsorted_median(self):
        """
            test median
        """
        from random import shuffle 
        values = range(10)
        shuffle(values)
        self.assertEqual(unsorted_median(values), 4.5)

        values.append(10)
        self.assertEqual(unsorted_median(values), 5)
        
        values = list("abcdefghi")
        shuffle(values)
        self.assertEqual(unsorted_median(values), 'e')
        
        values.extend('jk')
        self.assertEqual(unsorted_median(values), 'f')
        
#
#   debug code not run if called as a module
#     
if __name__ == '__main__':
    unittest.main()

